#include "selfinfowidget.h"
#include <QEvent>
#include <QMouseEvent>
#include <QGridLayout>
#include <QTimer>
#include <QFileDialog>

#include "model/datacenter.h"
#include "debug.h"
#include "toast.h"

using namespace model;

SelfInfoWidget::SelfInfoWidget(QWidget* parent)
    : QDialog(parent)
{
    // 1. 设置整个窗口的属性
    this->setFixedSize(400, 250);
    this->setWindowTitle("个人信息");
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));
    this->setStyleSheet("QWidget { background-color: rgb(255, 255, 255); }");
    // 窗口被关闭，自动销毁对话框对象
    this->setAttribute(Qt::WA_DeleteOnClose);
    // 把窗口移动到鼠标当前的位置
    this->move(QCursor::pos());

    // 2. 创建布局管理器
    layout = new QGridLayout();
    // layout->setSpacing(0);
    layout->setHorizontalSpacing(10);
    layout->setVerticalSpacing(0);
    layout->setContentsMargins(25, 10, 20, 0);
    layout->setAlignment(Qt::AlignTop);
    this->setLayout(layout);

    // 3. 创建头像
    avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(60, 60);
    avatarBtn->setIconSize(QSize(60, 60));
    // avatarBtn->setIcon(QIcon(":/resource/image/Whitey.jpg"));
    avatarBtn->setStyleSheet("QPushButton { border: none; background-color: transparent; }");
    layout->addWidget(avatarBtn, 0, 0, 3, 1);

    QString labelStyle = "QLabel { font-size: 14px; font-weight: 700; color: rgb(127, 127, 127); }";
    QString btnStyle = "QPushButton { border: none; background-color: transparent; }";
    btnStyle += "QPushButton:pressed { icon: url(':/resource/image/modify_clicked.png'); }";
    QString editStyle = "QLineEdit {  border: 1px solid rgb(242, 242, 242); "
                        "border-radius: 8px; padding-left: 5px; }";
    QString labelStyle2 = "QLabel { font-size: 13px; }";

    int height = 30;

    // 4. 添加用户的 id 的显示
    idTag = new QLabel();
    idTag->setFixedSize(50, height);
    idTag->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    idTag->setText("VQ");
    idTag->setStyleSheet(labelStyle);

    idLabel = new QLabel();
    idLabel->setFixedHeight(height);
    idLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    idLabel->setStyleSheet(labelStyle2);

    // 5. 添加用户的名字的显示
    nameTag = new QLabel();
    nameTag->setFixedSize(50, height);
    nameTag->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    nameTag->setText("昵称");
    nameTag->setStyleSheet(labelStyle);

    nameLabel = new QLabel();
    nameLabel->setFixedHeight(height);
    nameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    nameLabel->setStyleSheet(labelStyle2);


    nameModifyBtn = new QPushButton();
    nameModifyBtn->setFixedSize(80, 25);
    nameModifyBtn->setIconSize(QSize(20, 20));
    nameModifyBtn->setIcon(QIcon(":/resource/image/modify.png"));
    nameModifyBtn->setStyleSheet(btnStyle);


    nameEdit = new QLineEdit();
    nameEdit->setFixedHeight(height - 5);
    nameEdit->hide();
    nameEdit->setStyleSheet(editStyle);

    nameSubmitBtn = new QPushButton();
    nameSubmitBtn->setFixedSize(80, 25);
    nameSubmitBtn->setIconSize(QSize(20, 20));
    nameSubmitBtn->setIcon(QIcon(":/resource/image/submit.png"));
    nameSubmitBtn->setStyleSheet(btnStyle);
    nameSubmitBtn->hide();

    // 6. 个性签名
    descTag = new QLabel();
    descTag->setFixedSize(50, height);
    descTag->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    descTag->setText("签名");
    descTag->setStyleSheet(labelStyle);

    descLabel = new QLabel();
    descLabel->setFixedHeight(height);
    descLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    descLabel->setStyleSheet(labelStyle2);

    descModifyBtn = new QPushButton();
    descModifyBtn->setFixedSize(80, 25);
    descModifyBtn->setIconSize(QSize(20, 20));
    descModifyBtn->setIcon(QIcon(":/resource/image/modify.png"));
    descModifyBtn->setStyleSheet(btnStyle);

    descEdit = new QLineEdit();
    descEdit->setFixedHeight(height - 5);
    descEdit->hide();
    descEdit->setStyleSheet(editStyle);

    descSubmitBtn = new QPushButton();
    descSubmitBtn->setFixedSize(80, 25);
    descSubmitBtn->setIconSize(QSize(20, 20));
    descSubmitBtn->setIcon(QIcon(":/resource/image/submit.png"));
    descSubmitBtn->setStyleSheet(btnStyle);
    descSubmitBtn->hide();

    // 7. 添加电话
    phoneTag = new QLabel();
    phoneTag->setFixedSize(50, height);
    phoneTag->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    phoneTag->setText("电话");
    phoneTag->setStyleSheet(labelStyle);

    phoneLabel = new QLabel();
    phoneLabel->setFixedHeight(height);
    phoneLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    phoneLabel->setStyleSheet(labelStyle2);

    phoneModifyBtn = new QPushButton();
    phoneModifyBtn->setFixedSize(80, 25);
    phoneModifyBtn->setIconSize(QSize(20, 20));
    phoneModifyBtn->setIcon(QIcon(":/resource/image/modify.png"));
    phoneModifyBtn->setStyleSheet(btnStyle);

    phoneEdit = new QLineEdit();
    phoneEdit->setFixedHeight(height - 5);
    phoneEdit->hide();
    phoneEdit->setStyleSheet(editStyle);

    phoneSubmitBtn = new QPushButton();
    phoneSubmitBtn->setFixedSize(80, 25);
    phoneSubmitBtn->setIconSize(QSize(20, 20));
    phoneSubmitBtn->setIcon(QIcon(":/resource/image/submit.png"));
    phoneSubmitBtn->setStyleSheet(btnStyle);
    phoneSubmitBtn->hide();

    // 8. 添加验证码
    verifyCodeTag = new QLabel();
    verifyCodeTag->setFixedSize(50, height);
    verifyCodeTag->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    verifyCodeTag->setText("验证码");
    verifyCodeTag->setStyleSheet(labelStyle);
    verifyCodeTag->hide();

    verifyCodeEdit = new QLineEdit();
    verifyCodeEdit->setFixedSize(80, 25);
    verifyCodeEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    verifyCodeEdit->setStyleSheet(editStyle);
    verifyCodeEdit->hide();

    getVerifyCodeBtn = new QPushButton();
    getVerifyCodeBtn->setText("获取验证码");
    getVerifyCodeBtn->setStyleSheet("QPushButton { border: none; background-color: rgb(242, 242, 242); "
                                    "border-radius: 5px; }"
                                    "QPushButton:pressed { background-color: rgb(230, 230, 230); }");
    getVerifyCodeBtn->setFixedSize(95, 32);
    getVerifyCodeBtn->hide();

    // 9. 添加到布局管理器
    layout->addWidget(idTag, 0, 1);
    layout->addWidget(idLabel, 0, 2);

    layout->addWidget(nameTag, 1, 1);
    layout->addWidget(nameLabel, 1, 2);
    layout->addWidget(nameModifyBtn, 1, 3);

    layout->addWidget(descTag, 2, 1);
    layout->addWidget(descLabel, 2, 2);
    layout->addWidget(descModifyBtn, 2, 3);

    layout->addWidget(phoneTag, 3, 1);
    layout->addWidget(phoneLabel, 3, 2);
    layout->addWidget(phoneModifyBtn, 3, 3);

    layout->addWidget(verifyCodeTag, 4, 1);
    layout->addWidget(verifyCodeEdit, 4, 2);
    layout->addWidget(getVerifyCodeBtn, 4, 3);

#if TEST_UI
    idLabel->setText("2308711715");
    nameLabel->setText("小白");
    descLabel->setText("天天有骨头吃!");
    phoneLabel->setText("19212345678");

#endif

    // 10. 连接信号槽
    initSingalSlot();

    // 11. 加载数据到界面上
    DataCenter* dataCenter = DataCenter::getInstance();
    UserInfo* myself = dataCenter->getMyself();
    if (myself != nullptr)
    {
        // 显示个人信息到界面上
        avatarBtn->setIcon(myself->avatar);
        idLabel->setText(myself->userId);
        nameLabel->setText(myself->nickname);
        descLabel->setText(myself->description);
        phoneLabel->setText(myself->phone);
    }
}

void SelfInfoWidget::initSingalSlot()
{
    connect(nameModifyBtn, &QPushButton::clicked, this, [=](){
        // 隐藏 nameLabel 和 nameModifyButton
        nameLabel->hide();
        nameModifyBtn->hide();
        layout->removeWidget(nameLabel);
        layout->removeWidget(nameModifyBtn);

        // 显示 nameEdit 和 nameSubmitBtn
        nameEdit->show();
        nameSubmitBtn->show();
        layout->addWidget(nameEdit, 1, 2);
        layout->addWidget(nameSubmitBtn, 1, 3);

        // 设置输入框内容
        nameEdit->setText(nameLabel->text());
    });

    connect(descModifyBtn, &QPushButton::clicked, this, [=](){
        descLabel->hide();
        descModifyBtn->hide();
        layout->removeWidget(descLabel);
        layout->removeWidget(descModifyBtn);

        descEdit->show();
        descSubmitBtn->show();
        layout->addWidget(descEdit, 2, 2);
        layout->addWidget(descSubmitBtn, 2, 3);

        descEdit->setText(descLabel->text());
    });

    connect(phoneModifyBtn, &QPushButton::clicked, this, [=](){
        phoneLabel->hide();
        phoneModifyBtn->hide();
        layout->removeWidget(phoneLabel);
        layout->removeWidget(phoneModifyBtn);

        phoneEdit->show();
        phoneSubmitBtn->show();
        layout->addWidget(phoneEdit, 3, 2);
        layout->addWidget(phoneSubmitBtn, 3, 3);

        verifyCodeTag->show();
        verifyCodeEdit->show();
        getVerifyCodeBtn->show();
        layout->addWidget(verifyCodeTag, 4, 1);
        layout->addWidget(verifyCodeEdit, 4, 2);
        layout->addWidget(getVerifyCodeBtn, 4, 3);

        phoneEdit->setText(phoneLabel->text());
    });

    connect(nameSubmitBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickNameSubmitBtn);
    connect(descSubmitBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickDescSubmitBtn);
    connect(getVerifyCodeBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickGetVerifyCodeBtn);
    connect(phoneSubmitBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickPhoneSubmitBtn);
    connect(avatarBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickAvatarBtn);
}

void SelfInfoWidget::clickNameSubmitBtn()
{
    // 1. 从输入框中 拿到修改后的昵称
    const QString& nickname = nameEdit->text();
    if (nickname.isEmpty())
        return;

    // 2. 发送网络请求
    DataCenter* dataCenter = DataCenter::getInstance();
    connect(dataCenter, &DataCenter::changeNicknameDone, this,
            &::SelfInfoWidget::clickNameSubmitBtnDone, Qt::UniqueConnection);
    dataCenter->changeNicknameAsync(nickname);
}

void SelfInfoWidget::clickNameSubmitBtnDone()
{
    // 对界面控件进行切换 把刚才输入框切换回 label 把提交按钮切换回编辑按钮
    // 同时还需要把输入框中的文本设置为 label 中的文本
    layout->removeWidget(nameEdit);
    nameEdit->hide();
    layout->addWidget(nameLabel, 1, 2);
    nameLabel->show();
    nameLabel->setText(nameEdit->text());

    layout->removeWidget(nameSubmitBtn);
    nameSubmitBtn->hide();
    layout->addWidget(nameModifyBtn, 1, 3);
    nameModifyBtn->show();
}

void SelfInfoWidget::clickDescSubmitBtn()
{
    // 1. 从输入框中 拿到修改后的昵称
    const QString& desc = descEdit->text();
    if (desc.isEmpty())
        return;

    // 2. 发送网络请求
    DataCenter* dataCenter = DataCenter::getInstance();
    connect(dataCenter, &DataCenter::changeDescriptionDone, this,
            &::SelfInfoWidget::clickDescSubmitBtnDone, Qt::UniqueConnection);
    dataCenter->changeDescriptionAsync(desc);
}

void SelfInfoWidget::clickDescSubmitBtnDone()
{
    layout->removeWidget(descEdit);
    descEdit->hide();
    layout->addWidget(descLabel, 2, 2);
    descLabel->show();
    descLabel->setText(descEdit->text());

    layout->removeWidget(descSubmitBtn);
    descSubmitBtn->hide();
    layout->addWidget(descModifyBtn, 2, 3);
    descModifyBtn->show();
}

void SelfInfoWidget::clickGetVerifyCodeBtn()
{
    // 1. 从输入框中 拿到修改后的手机号
    const QString& phone = phoneEdit->text();
    if (phone.isEmpty())
        return;

    // 2. 发送网络请求
    DataCenter* dataCenter = DataCenter::getInstance();
    connect(dataCenter, &DataCenter::getVerifyCodeDone, this, [=](){
        Toast::showMessage("短信验证码已发送");
    });
    dataCenter->getVerifyCodeAsync(phone);

    // 3. 保存新的手机号码
    this->phoneToChange = phone;

    // 4. 禁用发送验证码按钮 倒计时
    this->getVerifyCodeBtn->setEnabled(false);

    leftTime = 60;
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [=](){
        if (leftTime <= 1)
        {
            getVerifyCodeBtn->setEnabled(true);
            getVerifyCodeBtn->setText("获取验证码");
            timer->stop();
            timer->deleteLater();
            return;
        }
        --leftTime;
        getVerifyCodeBtn->setText(QString::number(leftTime) + "s");
    });
    timer->start(1000);
}

void SelfInfoWidget::clickPhoneSubmitBtn()
{
    // 1. 先判定 当前验证码是否已经收到
    DataCenter* dataCenter = DataCenter::getInstance();
    QString verifyCodeId = dataCenter->getVerifyCodeId();
    if (verifyCodeId.isEmpty())
    {
        // 服务还没有返回验证码响应
        Toast::showMessage("服务器尚未返回响应, 稍后重试");
        return;
    }
    // 如果当前已经拿到 verifyCodeId 就清空 DataCenter 中存储的值
    dataCenter->resetVerifyCodeId("");

    // 2. 获取到用户输入的验证码
    QString verifyCode = verifyCodeEdit->text();
    if (verifyCode.isEmpty())
    {
        Toast::showMessage("验证码为空!");
        return;
    }
    verifyCodeEdit->setText("");    // 清空验证码

    // 3. 发送请求 把当前验证码信息 发送给服务器
    connect(dataCenter, &DataCenter::changePhoneDone, this,
            &SelfInfoWidget::clickPhoneSubmitBtnDone, Qt::UniqueConnection);
    dataCenter->changePhoneAsync(this->phoneToChange, verifyCodeId, verifyCode);

    // 4. 停止倒计时
    leftTime = 1;


}

void SelfInfoWidget::clickPhoneSubmitBtnDone()
{
    layout->removeWidget(verifyCodeTag);
    layout->removeWidget(verifyCodeEdit);
    layout->removeWidget(getVerifyCodeBtn);
    layout->removeWidget(phoneEdit);
    layout->removeWidget(phoneSubmitBtn);
    verifyCodeTag->hide();
    verifyCodeEdit->hide();
    getVerifyCodeBtn->hide();
    phoneEdit->hide();
    phoneSubmitBtn->hide();

    layout->addWidget(phoneLabel, 3, 2);
    phoneLabel->show();
    phoneLabel->setText(this->phoneToChange);
    layout->addWidget(phoneModifyBtn, 3, 3);
    phoneModifyBtn->show();
}

void SelfInfoWidget::clickAvatarBtn()
{
    // 1. 弹出对话框 选择文件
    QString filter = "Image Files (*.png *.jpg *.jpeg)";
    QString imagePath = QFileDialog::getOpenFileName(this, "选择头像", QDir::homePath(), filter);
    if (imagePath.isEmpty())
    {
        // 用户取消
        LOG("用户未选择任何头像");
        return;
    }

    // 2. 根据路径 读取到图片的内容
    QByteArray imageBytes = loadFileToByteArray(imagePath);

    // 3. 发送请求 修改头像
    DataCenter* dataCentr = DataCenter::getInstance();
    connect(dataCentr, &DataCenter::changeAvatarDone, this,
            &SelfInfoWidget::clickAvatarBtnDone, Qt::UniqueConnection);
    dataCentr->changeAvatarAsync(imageBytes);
}

void SelfInfoWidget::clickAvatarBtnDone()
{
    // 更新头像
    DataCenter* dataCenter = DataCenter::getInstance();
    avatarBtn->setIcon(dataCenter->getMyself()->avatar);
}





